<template>
  <div class="workspace-manager">
    <!-- 工作空间选择器 -->
    <el-dropdown @command="handleWorkspaceCommand" trigger="click">
      <el-button type="primary" class="workspace-selector">
        <el-icon><OfficeBuilding /></el-icon>
        {{ currentWorkspace?.name || '选择工作空间' }}
        <el-icon class="el-icon--right"><ArrowDown /></el-icon>
      </el-button>
      
      <template #dropdown>
        <el-dropdown-menu>
          <!-- 工作空间列表 -->
          <el-dropdown-item 
            v-for="workspace in workspaces" 
            :key="workspace.id"
            :command="`switch:${workspace.id}`"
            :class="{ 'is-active': currentWorkspace?.id === workspace.id }"
          >
            <div class="workspace-item">
              <el-icon :color="workspace.color">
                <component :is="workspace.icon" />
              </el-icon>
              <div class="workspace-info">
                <div class="workspace-name">{{ workspace.name }}</div>
                <div class="workspace-desc">{{ workspace.description }}</div>
              </div>
            </div>
          </el-dropdown-item>
          
          <el-dropdown-item divided command="manage">
            <el-icon><Setting /></el-icon>
            管理工作空间
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- 工作空间管理对话框 -->
    <el-dialog 
      v-model="showManageDialog" 
      title="工作空间管理" 
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="workspace-management">
        <!-- 工作空间列表 -->
        <div class="workspace-list">
          <div class="list-header">
            <h3>我的工作空间</h3>
            <el-button type="primary" @click="showCreateDialog = true">
              <el-icon><Plus /></el-icon>
              新建工作空间
            </el-button>
          </div>
          
          <el-table :data="workspaces" style="width: 100%">
            <el-table-column label="工作空间" min-width="200">
              <template #default="{ row }">
                <div class="workspace-item">
                  <el-icon :color="row.color">
                    <component :is="row.icon" />
                  </el-icon>
                  <div class="workspace-info">
                    <div class="workspace-name">{{ row.name }}</div>
                    <div class="workspace-desc">{{ row.description }}</div>
                  </div>
                </div>
              </template>
            </el-table-column>
            
            <el-table-column label="创建时间" width="150">
              <template #default="{ row }">
                {{ formatDate(row.createdAt) }}
              </template>
            </el-table-column>
            
            <el-table-column label="最后更新" width="150">
              <template #default="{ row }">
                {{ formatDate(row.updatedAt) }}
              </template>
            </el-table-column>
            
            <el-table-column label="操作" width="200">
              <template #default="{ row }">
                <el-button 
                  size="small" 
                  @click="switchWorkspace(row.id)"
                  :type="currentWorkspace?.id === row.id ? 'success' : 'default'"
                >
                  {{ currentWorkspace?.id === row.id ? '当前' : '切换' }}
                </el-button>
                
                <el-button size="small" @click="editWorkspace(row)">
                  编辑
                </el-button>
                
                <el-button 
                  size="small" 
                  type="danger" 
                  @click="deleteWorkspace(row.id)"
                  :disabled="row.name === '默认工作空间'"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <!-- 导入导出 -->
        <div class="import-export">
          <h3>导入/导出</h3>
          <el-space>
            <el-button @click="exportCurrentWorkspace">
              <el-icon><Download /></el-icon>
              导出当前工作空间
            </el-button>
            
            <el-upload
              :show-file-list="false"
              :before-upload="importWorkspace"
              accept=".json"
            >
              <el-button>
                <el-icon><Upload /></el-icon>
                导入工作空间
              </el-button>
            </el-upload>
          </el-space>
        </div>
      </div>
    </el-dialog>

    <!-- 创建/编辑工作空间对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      :title="editingWorkspace ? '编辑工作空间' : '新建工作空间'"
      width="500px"
    >
      <el-form :model="workspaceForm" :rules="workspaceRules" ref="workspaceFormRef">
        <el-form-item label="名称" prop="name">
          <el-input v-model="workspaceForm.name" placeholder="请输入工作空间名称" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="workspaceForm.description" 
            type="textarea" 
            placeholder="请输入工作空间描述"
            :rows="3"
          />
        </el-form-item>
        
        <el-form-item label="图标" prop="icon">
          <el-select v-model="workspaceForm.icon" placeholder="选择图标">
            <el-option 
              v-for="icon in iconOptions" 
              :key="icon.value" 
              :label="icon.label" 
              :value="icon.value"
            >
              <el-icon><component :is="icon.value" /></el-icon>
              {{ icon.label }}
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="颜色" prop="color">
          <el-color-picker v-model="workspaceForm.color" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="saveWorkspace">
          {{ editingWorkspace ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  OfficeBuilding,
  ArrowDown,
  Setting,
  Plus,
  Download,
  Upload
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, computed } from 'vue'
import { useWorkspaceStore, type WorkspaceConfig } from '@/stores/workspaceStore'

const workspaceStore = useWorkspaceStore()

// 响应式数据
const showManageDialog = ref(false)
const showCreateDialog = ref(false)
const editingWorkspace = ref<WorkspaceConfig | null>(null)
const workspaceFormRef = ref()

// 计算属性
const currentWorkspace = computed(() => workspaceStore.currentWorkspace)
const workspaces = computed(() => workspaceStore.workspaces)

// 表单数据
const workspaceForm = reactive({
  name: '',
  description: '',
  icon: 'OfficeBuilding',
  color: '#409eff'
})

// 表单验证规则
const workspaceRules = {
  name: [
    { required: true, message: '请输入工作空间名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 100, message: '描述不能超过100个字符', trigger: 'blur' }
  ]
}

// 图标选项
const iconOptions = [
  { label: '办公楼', value: 'OfficeBuilding' },
  { label: '房屋', value: 'House' },
  { label: '显示器', value: 'Monitor' },
  { label: '数据分析', value: 'DataAnalysis' },
  { label: '趋势图表', value: 'TrendCharts' }
]

// 处理工作空间命令
function handleWorkspaceCommand(command: string) {
  if (command === 'manage') {
    showManageDialog.value = true
  } else if (command.startsWith('switch:')) {
    const workspaceId = command.replace('switch:', '')
    workspaceStore.switchWorkspace(workspaceId)
    ElMessage.success('工作空间切换成功')
  }
}

// 切换工作空间
function switchWorkspace(id: string) {
  workspaceStore.switchWorkspace(id)
  ElMessage.success('工作空间切换成功')
}

// 编辑工作空间
function editWorkspace(workspace: WorkspaceConfig) {
  editingWorkspace.value = workspace
  Object.assign(workspaceForm, {
    name: workspace.name,
    description: workspace.description,
    icon: workspace.icon,
    color: workspace.color
  })
  showCreateDialog.value = true
}

// 保存工作空间
async function saveWorkspace() {
  try {
    await workspaceFormRef.value.validate()
    
    if (editingWorkspace.value) {
      // 更新现有工作空间
      workspaceStore.updateWorkspace(editingWorkspace.value.id, {
        name: workspaceForm.name,
        description: workspaceForm.description,
        icon: workspaceForm.icon,
        color: workspaceForm.color
      })
      ElMessage.success('工作空间更新成功')
    } else {
      // 创建新工作空间
      workspaceStore.createWorkspace({
        name: workspaceForm.name,
        description: workspaceForm.description,
        icon: workspaceForm.icon,
        color: workspaceForm.color,
        config: {}
      })
      ElMessage.success('工作空间创建成功')
    }
    
    showCreateDialog.value = false
    resetForm()
  } catch (error) {
    console.error('保存工作空间失败:', error)
  }
}

// 删除工作空间
async function deleteWorkspace(id: string) {
  try {
    await ElMessageBox.confirm('确定要删除这个工作空间吗？', '确认删除', {
      type: 'warning'
    })
    
    workspaceStore.deleteWorkspace(id)
    ElMessage.success('工作空间删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

// 导出当前工作空间
function exportCurrentWorkspace() {
  if (!currentWorkspace.value) {
    ElMessage.warning('没有当前工作空间')
    return
  }
  
  const config = workspaceStore.exportWorkspace(currentWorkspace.value.id)
  if (config) {
    const blob = new Blob([config], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `${currentWorkspace.value.name}_workspace.json`
    a.click()
    URL.revokeObjectURL(url)
    
    ElMessage.success('工作空间导出成功')
  }
}

// 导入工作空间
function importWorkspace(file: File) {
  const reader = new FileReader()
  reader.onload = (e) => {
    try {
      const config = e.target?.result as string
      const success = workspaceStore.importWorkspace(config)
      
      if (success) {
        ElMessage.success('工作空间导入成功')
      } else {
        ElMessage.error('工作空间导入失败')
      }
    } catch (error) {
      ElMessage.error('文件格式错误')
    }
  }
  reader.readAsText(file)
  return false // 阻止自动上传
}

// 重置表单
function resetForm() {
  editingWorkspace.value = null
  Object.assign(workspaceForm, {
    name: '',
    description: '',
    icon: 'OfficeBuilding',
    color: '#409eff'
  })
}

// 格式化日期
function formatDate(dateString: string) {
  return new Date(dateString).toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.workspace-selector {
  min-width: 160px;
}

.workspace-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.workspace-info {
  flex: 1;
}

.workspace-name {
  font-weight: 500;
  font-size: 14px;
}

.workspace-desc {
  font-size: 12px;
  color: #666;
  margin-top: 2px;
}

.workspace-management {
  max-height: 600px;
  overflow-y: auto;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.import-export {
  margin-top: 24px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.is-active {
  background-color: #f0f9ff;
  color: #409eff;
}
</style>
